const express=require('express');
const multer=require('multer');
const body=require('body-parser');
const mysql=require('mysql');

let db=mysql.createPool({
  host:'localhost',
  port:'3306',
  user:'root',
  password:'',
  database:'20180209'
});

let server=express();

server.listen(8080);

server.use(body.urlencoded({extended: false}));
let multerObj=multer({dest: './upload/'});
server.use(multerObj.any());

server.use('/api', (req, res)=>{
  if(req.headers['origin']=='null' || req.headers['origin'].startsWith('http://localhost')){
    res.setHeader('Access-Control-Allow-Origin','*');
  }

  // res.send('OK');
  console.log(req.files);
  let arr=[];
  req.files.forEach(file=>{
    arr.push(`('${file.originalname}', '${file.filename}', '${Math.floor(Date.now()/1000)}')`);
  });
  let sql=`INSERT INTO images_table (originalname, filename, date) VALUES${arr.join(',')}`;
  db.query(sql, err=>{
    if(err){
      res.send('database error');
    }else{
      res.send('ok');
    }
  });
});

server.use(express.static('./www/'));
